<template>
  <div>
    <form class="search-form"
          action="/">
      <van-search v-model="searchText"
                  shape="round"
                  show-action
                  background="#4fc08d"
                  placeholder="请输入搜索关键词"
                  @search="onSearch"
                  @focus="isResulShow = false"
                  @cancel="onCancel" />

    </form>
    <search-result :search-text="searchText"
                   v-if="isResulShow"></search-result>
    <search-suggestion v-else-if="searchText"
                       :search-text="searchText"
                       @search="onSearch"></search-suggestion>
    <search-history v-else
                    :search-histories="searchHistories"
                    @clear-search-histories="searchHistories = []"
                    @search="onSearch"></search-history>

  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setToken, getToken } from '@/utils/storage.js'
export default {
  name: 'searchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResulShow: false,
      searchHistories: getToken('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)

      this.isResulShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  watch: {
    searchHistories (value) {
      setToken('TOUTIAO_SEARCH_HISTORIES', value)
    }
  }
}
</script>

<style lang="less" scoped>
.search-form {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}
.search-result,
.search-history,
.search-suggestion {
  margin-top: 109px;
}
.van-search__action {
  background-color: #fff;
  padding: 0 10px;
  border-radius: 50%;
  margin: 0 15px;
  font-size: 12px;
  color: #858585;
}
</style>
